<template>
  <div class="password-change-wrapper">
    <div class="password-change-card">
      <h2>修改密码</h2>
      <form @submit.prevent="submitForm" class="password-form">
        <div class="form-group">
          <label for="newPassword">新密码</label>
          <input
              type="password"
              id="newPassword"
              v-model="form.newPassword"
              placeholder="请输入新密码"
              required
          />
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
              type="password"
              id="confirmPassword"
              v-model="form.confirmPassword"
              placeholder="请再次输入新密码"
              required
          />
        </div>
        <div class="button-group">
          <button type="button" class="cancel-btn" @click="goBack">取消</button>
          <button type="submit" class="submit-btn">提交</button>
        </div>
      </form>
      <p v-if="message" :class="['message', message.type]">{{ message.text }}</p >
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios'; // 直接导入 axios

const router = useRouter();

// 表单数据
const form = ref({
  newPassword: '',
  confirmPassword: '',
});

// 消息提示
const message = ref(null);

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// JWT 解析函数
const getSub = (token) => {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) throw new Error('Invalid JWT format');

    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
    return payload.sub || null;
  } catch (error) {
    console.error('Failed to parse JWT:', error);
    return null;
  }
};

// 提交表单函数
const submitForm = async () => {
  // 重置消息
  message.value = null;

  // 验证密码是否一致
  if (form.value.newPassword !== form.value.confirmPassword) {
    message.value = { type: 'error', text: '两次输入的密码不一致！' };
    return;
  }

  // 验证密码长度
  if (form.value.newPassword.length < 6) {
    message.value = { type: 'error', text: '密码长度至少6位！' };
    return;
  }

  try {
    // 获取 JWT token
    const token = sessionStorage.getItem('jwt');
    if (!token) {
      message.value = { type: 'error', text: '用户未登录！' };
      return;
    }

    // 解析用户名
    const curUsername = getSub(token);
    if (!curUsername) {
      message.value = { type: 'error', text: '用户信息获取失败！' };
      return;
    }

    // 使用 axios 直接发送请求
    const response = await axios.post('/password', {
      username: curUsername,
      password: form.value.newPassword,
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.slice(1,-1)}`  // 添加认证令牌
      }
    });

    if (response.status === 200) {
      message.value = { type: 'success', text: '密码修改成功！' };
      form.value.newPassword = '';
      form.value.confirmPassword = '';

      // 3秒后自动返回
      setTimeout(() => {
        router.go(-1);
      }, 3000);
    }
  } catch (err) {
    console.error('修改密码失败:', err);

    if (err.response) {
      // 服务器返回的错误
      const errorMsg = err.response.data?.message || '修改密码失败';
      message.value = { type: 'error', text: errorMsg };
    } else if (err.request) {
      // 网络错误
      message.value = { type: 'error', text: '网络错误，请检查连接！' };
    } else {
      // 其他错误
      message.value = { type: 'error', text: '修改密码失败，请重试！' };
    }
  }
};
</script>

<style>
/* 全局居中布局 */
.password-change-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 卡片样式 */
.password-change-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.password-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: bold;
  color: #555;
}

input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #007bff;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  flex: 1;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #0056b3;
}

.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* 消息提示 */
.message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #e6ffed;
  color: #1a7324;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffa4a4;
}
</style>